package com.sphd.emanu.activity.arrivetime;

import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.sphd.emanu.R;
import com.sphd.emanu.adapter.ArriveTimeAdapter;
import com.sphd.emanu.config.Constant;
import com.sphd.emanu.mvp.MVPBaseActivity;
import com.sphd.emanu.pojo.login.User;
import com.sphd.emanu.pojo.market.ArriveTime;
import com.wzutils.L;
import com.wzutils.TimeUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * //todo 送餐时间的设定
 *
 * @Author Hu
 * @Time 2017/6/15 -- 14:57.
 * @Email 87683202@qq.com
 */
public class ArriveTimeActivity extends MVPBaseActivity<ArriveTimeContract.View, ArriveTimePresenter> implements ArriveTimeContract.View {
    Intent intent;
    Bundle bundle;
    User user;
    @BindView(R.id.add_time)
    TextView addTime;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.my_recycler)
    RecyclerView myRecycler;
    @BindView(R.id.my_swf)
    SwipeRefreshLayout mySwf;
    ArriveTimeAdapter arriveTimeAdapter;
    private int mHour;
    private int mMinute;
    private Calendar c;
    private TimePickerDialog timePickerDialog;
    View dialogView;
    private AlertDialog offserDialog;
    private MaterialEditText myEdit;
    TextView title;
    Button btnConfirm, btnCancle;
    boolean isUpData = false;
    int offset = 0;
    int pos = 0;
    boolean isCanDo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_arrive_time);
        ButterKnife.bind(this);
        initView();
        initEvent();
    }

    private void initEvent() {
        toolbar.setNavigationOnClickListener(v -> finish());
        mySwf.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                addData();
            }
        });

        myRecycler.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemLongClick(BaseQuickAdapter adapter, View view, final int position) {
                super.onItemLongClick(adapter, view, position);
                final ArriveTime arriveTime = (ArriveTime) adapter.getItem(position);
                if (isCanDo)
                    new SweetAlertDialog(context, SweetAlertDialog.WARNING_TYPE).setTitleText("确定要删除吗？").setConfirmText("确定").setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            showProgressDialog();
                            mPresenter.deleteArriveTime(arriveTime.getId(), position, sweetAlertDialog);
                        }
                    }).setCancelText("取消").show();
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                final ArriveTime arriveTime = (ArriveTime) adapter.getItem(position);
                timePickerDialog.updateTime(arriveTime.getArriveTime().getHours(), arriveTime.getArriveTime().getMinutes());
                timePickerDialog.show();
                pos = position;
                offset = arriveTime.getOffset();
                isUpData = true;
            }
        });

        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(myEdit.getText().toString().trim())) {
                    toast("时间偏差值不能为空");
                } else {
                    showProgressDialog();
                    if (isUpData) {
                        ArriveTime arriveTime = arriveTimeAdapter.getItem(pos);
                        // TODO: 2017/6/19 明日解决此问题
                        mPresenter.updateArriveTime(arriveTime.getId(), new StringBuilder().append(
                                c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH)).
                                        append(" " + mHour).append(":")
                                        .append((mMinute < 10) ? "0" + mMinute : mMinute).append(":00").toString(),
                                Integer.valueOf(myEdit.getText().toString().trim()), pos);
                    } else {
                        mPresenter.addArriveTime(user.getOid(), new StringBuilder().append(
                                c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DAY_OF_MONTH)).
                                        append(" " + mHour).append(":")
                                        .append((mMinute < 10) ? "0" + mMinute : mMinute).append(":00").toString(),
                                Integer.valueOf(myEdit.getText().toString().trim()));
                    }
                }
            }
        });
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isUpData) {
                    isUpData = false;
                }
                offserDialog.dismiss();
            }
        });
    }

    private void initView() {
        setTitleBar(toolbar, "时间列表");
        intent = getIntent();
        bundle = intent.getExtras();
        user = (User) bundle.getSerializable(Constant.USER_ENTITY);
        isCanDo = bundle.getBoolean(Constant.IS_CANDO);
        if (!isCanDo) {
            addTime.setVisibility(View.GONE);
        }
        setRefresh(mySwf);
        initAdapter();
        initDialog();
        addData();
    }

    private void initDialog() {
        c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        timePickerDialog = new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, true);
        dialogView = View.inflate(context, R.layout.dialog_edit_myself, null);
        title = (TextView) dialogView.findViewById(R.id.title);
        offserDialog = getDialogBuilder(dialogView, R.style.AlertDialog);
        myEdit = (MaterialEditText) dialogView.findViewById(R.id.my_edit);
        btnConfirm = (Button) dialogView.findViewById(R.id.btn_confirm);
        btnCancle = (Button) dialogView.findViewById(R.id.btn_cancle);
    }

    private void initAdapter() {
        setRecy(myRecycler);
        arriveTimeAdapter = new ArriveTimeAdapter(R.layout.item_arrive_time, new ArrayList<ArriveTime>(), isCanDo);
        arriveTimeAdapter.setEmptyView(emptyView);
        myRecycler.setAdapter(arriveTimeAdapter);
    }

    private void addData() {
        showProgressDialog();
        mPresenter.selectArriveTime(user.getOid());
    }

    @Override
    public void setTimeList(List<ArriveTime> timeList) {
        arriveTimeAdapter.setNewData(timeList);
        dissProgressDialog();
    }

    @OnClick(R.id.add_time)
    public void onViewClicked() {
        if (timePickerDialog != null)
            timePickerDialog.show();
    }

    /**
     * 时间控件事件
     */
    private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mHour = hourOfDay;
            mMinute = minute;
            offserDialog.show();
            title.setText("设置时间偏差");
            if (isUpData) {
                myEdit.setText(String.valueOf(offset));
            } else {
                myEdit.setHint("请输入整数。");
            }
        }
    };

    @Override
    public void upRes(int res, Integer pos) {
        dissProgressDialog();
        if (res == 1) {
            isUpData = false;
            toast("操作成功");
            offserDialog.dismiss();
            addData();
        } else {
            toast("操作失败，请重试。");
        }
    }


    @Override
    public void setRes(int res) {
        dissProgressDialog();
        if (res == 1) {
            toast("操作成功");
            offserDialog.dismiss();
            addData();
        } else {
            toast("操作失败，请重试。");
        }
    }

    @Override
    public void delRes(int res, int pos, SweetAlertDialog sweetAlertDialog) {
        dissProgressDialog();
        if (res == 1) {
            toast("删除成功");
            arriveTimeAdapter.remove(pos);
            sweetAlertDialog.dismiss();
        } else {
            toast("删除失败");
        }
    }
}
